import {
	handleGlobalHooksQueue
} from './utils.js'

export default class XRouter {
	constructor() {
		this.beforeHooks = [];
		this.afterHooks = [];
		this.errorCbs = [];
		this.hanldeUniRoute(handleGlobalHooksQueue);
	}
	beforeEach(callback) {
		return this.registerHook(this.beforeHooks, callback);
	}

	afterEach(callback) {
		return this.registerHook(this.afterHooks, callback);
	}
	onError(errCb) {
		return this.registerHook(this.errorCbs, errCb);
	}
	// 存放回调
	registerHook(list, callback) {
		list.push(callback);
		return () => {
			const index = list.indexOf(callback);
			if (index !== -1) list.splice(index, 1);
		};
	};

	// 代理路由
	hanldeUniRoute(callback) {
		// 路由跳转的函数key值
		const UNI_ROUTE_ACTIONS = ['navigateTo', 'redirectTo', 'reLaunch', 'switchTab', 'navigateBack'];
		// 函数缓存容器,保存原函数引用
		const cacheFunc = {};
		UNI_ROUTE_ACTIONS.forEach((key) => {
			cacheFunc[key] = uni[key];
		});

		// 重写方法
		UNI_ROUTE_ACTIONS.forEach(key => {
			uni[key] = (opts, params, isCancelProxy) => {
				// 处理下参数
				if (opts && opts.url && !isCancelProxy) {
					let optsParams = opts.url.split("?");
					if (optsParams[1]) {
						let res = {};
						let paramArr = optsParams[1].split('&');
						paramArr.forEach((v, i) => {
							let str = v.split('=');
							res[str[0]] = str[1];
						})
						opts.url = optsParams[0]
						params = params ? Object.assign(params, res) : res
					}
					if (params) {
						let paramsData = ''
						Object.keys(params).forEach((key, i) => {
							paramsData += key + '=' + params[key] + (i !== Object.keys(params).length - 1 ? '&' : '');
						});
						opts.url = `${opts.url}?${paramsData}`
						opts.params = params
					}
				}

				// 取消拦截并直接运行
				if (isCancelProxy) {
					cacheFunc[key](opts);
				} else {
					// 处理所有钩子
					const defaultOpts = {
						action: key
					};
					const newOpts = Object.assign(defaultOpts, opts); //添加 action: key
					const actionFunc = function(customOpts) {
						const lastOpts = Object.assign(newOpts, customOpts);
						cacheFunc[lastOpts.action](lastOpts);
					};

					callback.call(this, newOpts, actionFunc);
				}
			};
		});
	}

}
XRouter.install = (Vue, opts = {}) => {};
